package com.example.product.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.core.domain.Result;
import com.example.product.entity.Product;
import com.example.product.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping("/{id}")
    public Result<Product> getById(@PathVariable Long id) {
        return Result.success(productService.getById(id));
    }

    @PostMapping
    public Result<Boolean> create(@RequestBody Product product) {
        return Result.success(productService.save(product));
    }

    @PutMapping
    public Result<Boolean> update(@RequestBody Product product) {
        return Result.success(productService.updateById(product));
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        return Result.success(productService.removeById(id));
    }

    @GetMapping
    public Result<Page<Product>> page(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name) {
        
        Page<Product> page = new Page<>(current, size);
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Product::getName, name);
        wrapper.orderByDesc(Product::getCreateTime);
        
        return Result.success(productService.page(page, wrapper));
    }

    @PostMapping("/{id}/stock/decrease")
    public Result<Boolean> decreaseStock(
            @PathVariable Long id,
            @RequestParam Integer quantity) {
        return Result.success(productService.decreaseStock(id, quantity));
    }
} 